<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Client\Action\Dashboard\Tag;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Client\Contract\ClientTagContract;
use MoChat\App\Client\Contract\ClientTagGroupContract;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\WorkContact\Contract\WorkContactTagContract;
use MoChat\App\WorkContact\Contract\WorkContactTagGroupContract;
use MoChat\App\WorkContact\QueueService\Tag\DeleteApply;
use MoChat\App\WorkContact\QueueService\Tag\StoreApply;
use MoChat\App\WorkContact\QueueService\Tag\UpdateApply;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 移动客户标签分组.
 *
 * Class Move
 * @Controller
 */
class Move extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var ClientTagContract
     */
    protected $workContactTagService;

    /**
     * @Inject
     * @var StoreApply
     */
    protected $storeApply;

    /**
     * @Inject
     * @var UpdateApply
     */
    protected $updateApply;

    /**
     * @Inject
     * @var DeleteApply
     */
    protected $deleteApply;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Inject
     * @var ClientTagGroupContract
     */
    private $contactTagGroupService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/clientTag/move", methods="PUT")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        // 接收参数
        $params['groups'] = $this->request->input('groups');
        // 验证参数
        $this->validated($params);
        // 数据操作
        Db::beginTransaction();
        try {
            foreach ($params['groups'] as $item) {
                $this->contactTagGroupService->updateWorkContactTagGroupById((int) $item['id'], ['order' => $item['order']]);
            }
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '引流链接创建失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'groups' => 'required|array',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'groups.required' => '分组 必传',
        ];
    }
}
